import execjs
import requests
from lxml import etree


def one():
    response = session.get(url, headers=headers)
    print("第一次响应码=>", response.status_code)
    print("第一次cookie值：", session.cookies)
    obj = etree.HTML(response.text)  # type: ignore
    ts_code = obj.xpath('//script[1]/text()')[0]
    content_code = obj.xpath('//meta[2]/@content')[0]
    func_src = 'https://www.zking.com' + obj.xpath('//script[2]/@src')[0]
    func_code = requests.get(func_src, headers=headers).text
    two(func_code, content_code, ts_code)


def two(func_code, content_code, ts_code):
    with open('main.js', encoding='utf-8') as f:
        code = f.read().replace('func_code', func_code).replace('content_code', content_code).replace('ts_code',
                                                                                                      ts_code)
    # print(code)
    res = execjs.compile(code).call('get_cookie')
    # print(res)
    res = res.split(';')[0].split('=')
    print(res)
    session.cookies[res[0]] = res[1]
    headers['Referer'] = url
    print("第二次cookie值：", session.cookies)
    response = session.get(url, headers=headers)
    response.encoding = response.apparent_encoding
    print("第二次响应码=>", response.status_code)
    print(response.text)


if __name__ == '__main__':
    url = 'https://www.zking.com'
    headers = {
        'Accept': '*/*',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',
    }
    session = requests.session()
    one()
